<template>
  <div class="the-page">
    <el-form ref="formRef" :rules="formRules" :model="upload.post" class="demo-form-inline" label-width="100px">

      <el-form-item label="设置发布者" required>
        <el-radio-group v-model="upload.otherData.creatorOrigin" @change="uploadFn.creatorOriginChange" :disabled="upload.status!==0" class="ml-4">
          <el-radio :label="1">选定用户</el-radio>
          <el-radio :label="2">随机用户</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="发布者" prop="customerId" v-if="upload.otherData.creatorOrigin===1">
        <el-select v-model="upload.post.customerId" :disabled="upload.status!==0" placeholder="请选择用户" style="width: 360px" filterable>
          <el-option v-for="item in props.customerList" :key="item.id" :label="`${item.id}-${item.name} (${item.phone})`" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="发布者" required v-else-if="upload.otherData.creatorOrigin===2">
        <el-select v-model="upload.otherData.creatorPull" :disabled="upload.status!==0" placeholder="请选择随机池" style="width: 360px" filterable>
          <el-option v-for="item in [{id:1,name:'马甲号随机'}]" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      
      <!-- <el-form-item label="标题" prop="title">
        <el-input v-model="upload.post.title" show-word-limit maxlength="15" placeholder="输入标题"></el-input>
      </el-form-item> -->

      <!-- <el-form-item label="描述" prop="description">
        <el-input v-model="upload.post.description" show-word-limit type="textarea" maxlength="1000" :rows="6" placeholder="输入内容描述"></el-input>
      </el-form-item> -->

      <el-form-item label="视频">
        <upload-aliyun-auth 
        v-model:uploadStatus="upload.statusName" 
        :disabled="upload.status!==0"
        :finishList="upload.finishList"
        @video:number="uploadFn.videoNumberBack"
        @image:info="uploadFn.imageInfoBack"
        @video:info="uploadFn.videoInfoBack"
        @video:success="uploadFn.videoSuccessBack"
        @image:success="uploadFn.imageSuccessBack"
        @video:fail="uploadFn.videoFailBack"
        @image:fail="uploadFn.imageFailBack"
        @upload:finish="uploadFn.finishBack"></upload-aliyun-auth>
        <p>*注意：视频文件名将作为标题上传（不超过十五个字符）</p>
      </el-form-item>

      <el-form-item label="位置" prop="location">
        <span>请输入经度：</span>
        <el-input-number style="width:240px;margin: 0 8px 8px 0;" v-model="upload.post.longitude" placeholder="请输入经度" controls-position="right" :disabled="upload.status!==0"></el-input-number>
        <span>请输入纬度：</span>
        <el-input-number style="width:240px;margin: 0 8px 8px 0;" v-model="upload.post.latitude" placeholder="请输入纬度" controls-position="right" :disabled="upload.status!==0"></el-input-number>
        <el-input v-model="upload.post.location" :disabled="upload.status!==0" placeholder="请输入位置地名"></el-input>
      </el-form-item>

      <el-form-item label="标签">
        <el-select v-model="upload.post.relatedTopic" :disabled="upload.status!==0" multiple placeholder="请选择话题标签" style="width: 360px" filterable>
          <el-option v-for="item in props.tagsList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>

      <el-form-item style="text-align:center">
        <el-button v-if="upload.status===0" type="primary" plain @click="uploadFn.submitPre(formRef)">提交</el-button>
        <el-button v-else-if="upload.status === 2" type="primary" plain @click="uploadFn.resetPost">重置</el-button>
      </el-form-item>

    </el-form>
    
  </div>
</template>
<script setup>
import uploadAliyunAuth from "@/components/Upload/aliyunVideoAuth";
import { ref, reactive, onMounted } from "vue";
import { uploadImageOrVideo } from "@/api/operation";
import { ElMessage } from 'element-plus';
const props = defineProps({
  customerList: {
    default: ()=>[],
    type: Object,
  },
  tagsList: {
    default: ()=>[],
    type: Object,
  },
})
const formRef = ref();
const formRules = reactive({
  customerId: [{ required: true, message: "请选择发布者", trigger: "change"}],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
});

const { $data: upload, $fn: uploadFn } = (() => {
  const backup = {
    // 公共post
    post:{
      type: "video",
      customerId: null,
      longitude: undefined,
      latitude: undefined,
      location: "",
      // musicId: "",
      // musicName: "",
      title: "",//标题
      description: "",//描述
      coverImageId: "",//封面图id
      relatedTopic: "",
      video: {
        videoId: "",
        format: "mp4",
        duration: 0,
        size: 0,
      },
    }
  }
  const $data = reactive({
    videoNumer: 0,//准备上传的视频的数量
    videoFinish: false,//视频是否上传完成
    contentNumber: 0,//当contentNumber===videoNumer时，表明作品上传完成
    post:{...backup.post},
    otherData:{
      creatorOrigin: 2,//1:选定用户,2:随机用户
      creatorPull: 1,//固定为1
    },
    postList:[],//存放上传数据
    coverList:[],//存放封面的信息
    status: 0,//0:未开始,1:上传中,2:已完成,
    statusName:"",//"upload":上传,"clear":清空
    finishList:[],//传递给上传组件的数据，表示对应项的上传状态，[0,1,2],0:未开始，1成功，2失败
  });
  const $fn = {
    videoNumberBack(num){
      console.log("上传的视频数量：",num);
      $data.videoNumer = num;
    },
    videoInfoBack(info,index){
      console.log("video info:",info,index);
      if(!info){$data.postList[index]=null;return;}
      $data.postList[index]={video:null};
      $data.postList[index].video={
        videoId: "",
        format: "mp4",
        duration: info?.duration||0,
        size: info?.size||0,
      }
      $data.postList[index].title = info.title||" 品客";
    },
    imageInfoBack(info,index){
      console.log("image info:",info,index);
      $data.coverList[index] = info;
    },
    videoSuccessBack(info,index,finish){
      console.log("video success:",info,index,finish);
      $data.postList[index].video.videoId = info.videoId;
      if(finish){
        // 开始上传作品
        // console.log(index+":video成功！videoId:",$data.postList[index].video.videoId,",imageId:",$data.postList[index].coverImageId);
        $fn.submitData(index);
      }
    },
    videoFailBack(err,index){
      if($data.finishList[index]!==2){
        $data.finishList[index] = 2;
        $data.contentNumber++;
      }
    },
    imageSuccessBack(info,index,finish){
      // console.log("image success:",info,index,finish);
      $data.postList[index].coverImageId = info.videoId;
      if(finish){
        // console.log(index+":img成功！videoId:",$data.postList[index].video.videoId,",imageId:",$data.postList[index].coverImageId);
        // 开始上传作品
        $fn.submitData(index);
      }
    },
    imageFailBack(err,index){
      if($data.finishList[index]!==2){
        $data.finishList[index] = 2;
        $data.contentNumber++;
      }
    },
    finishBack(){
      $data.videoFinish = true;
      // console.log("upload finish:");
    },

    submitPre(formRef) {
      if (!formRef) return;
      formRef.validate((valid) => {
        if (valid) {
          if(!$data.videoNumer){
            ElMessage.error("请选择视频！");
            return;
          }
          // 检验封面是否存在
          for(let i=0,len=$data.postList.length;i<len;i++){
            if($data.postList[i] && !$data.coverList[i]){
              ElMessage.warning("存在错误视频或封面图，请处理后再提交！");
              return;
            }
          }
          $data.statusName = "upload";
          $data.status = 1;
        }
      });
    },
    submitData(index) {
      // 数据验证
      let req = {
        ...$data.post,
        video: $data.postList[index].video,
        title: $data.postList[index].title,
        coverImageId: $data.postList[index].coverImageId,
        relatedTopic: (()=>{
          if(!$data.post.relatedTopic?.length){
            return "";
          }else{
            return $data.post.relatedTopic.join(",")
          }
        })(),
        customerId:(()=>{
          if($data.otherData.creatorOrigin===2){
            // 生成随机用户
            let len = props.customerList?.length||0;
            let random = ~~(Math.random()*len);
            return props.customerList[random].id;
          }else{
            return $data.post.customerId;
          }
        })()
      };
      console.log("upload req:",index,req);
      // return;
      uploadImageOrVideo(req).then((res) => {
        if (res.code === 0) {
          $data.finishList[index] = 1;
        }else{
          $data.finishList[index] = 2;
        }
        showResult();
      }).catch(err=>{
        $data.finishList[index] = 2;
        showResult();
      })

      function showResult(){
        $data.contentNumber++;
        if($data.contentNumber === $data.videoNumer){
         $data.status = 2;
          ElMessage.success("作品上传完成！");
        }
      }
    },
    resetPost(){
      $data.post = {...backup.post};
      $data.postList = [];
      $data.status = 0;//0:未开始,1:上传中,2:已完成,
      
      $data.videoNumer = 0;
      $data.contentNumber = 0;
      $data.videoFinish = false;
      $data.otherData.creatorOrigin = 2;
      $data.statusName = "clear";
    }
  }
  return {
    $data,
    $fn,
  }
})();
</script>
<script>
export default {
  name: "videoBatch",
};
</script>

<style scoped lang="scss">
.the-page{
  background-color: #ffffff;
  padding: 12px;
}
</style>